package cn.jrainbow.util;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport{
	public static String SUCCESS = "操作成功";
	private Integer start;
	private Integer limit;
	
	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}

	public Integer getLimit() {
		return limit;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}
	
	public void send(String message) throws IOException{
		ServletActionContext.getResponse().setContentType("application/x-json;charset=UTF-8");
		ServletActionContext.getResponse().getWriter().print(message);
	}
	
	/**
	 * 操作成功返回
	 * 
	 * @param okMsg
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void successResponse(String msg) throws Exception {
		jsonMsgResponse(msg, 0);
	}
	/**
	 * 操作失败返回
	 * 
	 * @param okMsg
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void failedResponse(String msg)  {
		jsonMsgResponse(msg, 1);
	}
	
	
	/**
	 * 返回
	 * 
	 * @param msg
	 * @param msgType
	 *            0为成功,其它为失败
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private static void jsonMsgResponse(String msg, int msgType){
		boolean scriptTag = false;
		String cb = ServletActionContext.getRequest().getParameter("callback");
		if (cb != null) {
			scriptTag = true;
			ServletActionContext.getResponse().setContentType("text/javascript;charset=UTF-8");
		} else {
			ServletActionContext.getResponse().setContentType("application/x-json;charset=UTF-8");
		}
		
		try {
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			if (scriptTag)
				out.write((new StringBuilder(String.valueOf(cb))).append("(")
						.toString());
			if (msgType == 0){
				out.print((new StringBuilder("{success:true,'info':'")).append(msg)
						.append("'}").toString());
			}else{
				out.print((new StringBuilder("{success:false,'errorInfo':'操作失败:"))
						.append(msg).append("'}").toString());
			}
				
			if (scriptTag){
				out.write(");");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
